package nc.bs.io.util;

import nc.bs.common.util.FileSuffix;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

/**
 * @author duanyp1
 * @date 2024/3/14 15:52
 */
public class FileUtil {

    public static File readFile(Class<?> clazz, String fileName, String suffix) {
        fileName = fileName.endsWith(suffix) ? fileName : fileName + suffix;
        URL url = Objects.requireNonNull(clazz.getResource("."));
        return new File(url.getPath() + fileName);
    }

    public static String readFileAsStringBySQL(Class<?> clazz, String fileName) {
        return readFileAsString(clazz,fileName, FileSuffix.sql);
    }

    public static String readFileAsString(Class<?> clazz, String fileName, String suffix) {
        File file = readFile(clazz, fileName, suffix);
        String sql = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder buffer = new StringBuilder();
            String data;
            while ((data = reader.readLine()) != null) {
                buffer.append(data);
            }
            sql = buffer.toString();
        } catch (IOException e) {
            ExceptionUtils.wrappException(e);
        }
        return sql;
    }

}
